<?php
namespace Reseller\Model;

/**
 * 订购中心游客信息录入
 */
class OrderCenter3Model extends BaseModel
{

    //游客信息录入页面数据展示
    public function writeInfo()
    {
        // dump(I('post.'));
        $re           = [];
        $up_insure_id = I('up_insure_id');
        $day          = I('day');
        $sprice_id    = I('sprice_id');
        $line_id      = I('line_id');
        $reseller_id  = session('reseller_user.pid') ? session('reseller_user.pid') : session('reseller_user.reseller_id');
        //线路信息
        $re['line'] = M('public_line')
            ->field('line_id,group_num,line_name,travel_days,line_sn,source_type,supplier_id,room_price_id,go_price_id,back_price_id,add_room_price,discounts_condition,discounts')
            ->where(['line_id' => $line_id])
            ->find();
        $this->line = $re['line'];
        //出团当天价格
        if ($sprice_id) {
            $re['price'] = M('operator_special_price')
                ->field('adult_price,child_price,oldman_price')
                ->where(['sprice_id' => $sprice_id])
                ->find();
        } else {
            $re['price'] = M('line_reseller_price')
                ->field('adult_price,child_price,oldman_price')
                ->where(['line_id' => $line_id,
                            [
                                ['reseller_id' => $reseller_id, 'rp_type' => session('reseller_user.shop_or_reseller')],
                                'rp_type' => 0, '_logic' => 'or'],
                        ])
                ->find();
        }

        //保险价格
        if ($up_insure_id) {
            $re['insure'] = M('line_upgrade_insure')
                ->field('up_insure_id,now_child_price,now_adult_price,insure_name')
                ->where(['up_insure_id' => $up_insure_id])
                ->find();
        }
        $product_id = I('product_id');
        //附加产品
        if (!empty($product_id)) {
            $product             = $this->addProduct();
            $re['product']       = $product['product'];
            $re['product_price'] = $product['product_price'];
        }

        $time_stamp = strtotime(substr($day, 0, 4) . '-' . substr($day, 4, 2) . '-' . substr($day, 6));

        $re['traffic_seat'] = $this->seatInfo($time_stamp, $line_id, $re['line']['travel_days']);

        $re['hotel'] = $this->hotelInfo($time_stamp, $line_id, $re['line']['travel_days']);

        if ($re['line']['source_type'] == 1) {
            $re['line']['supplier'] = '自营';
        } elseif ($re['line']['source_type'] == 2) {
            $re['line']['supplier'] = M('operator_line_supplier')
                ->where(['supplier_id' => $re['line']['supplier_id']])
                ->getField('supplier_name');
        }
        return $re;
    }

    /**
     * 附加产品列表
     * @return array [附加产品列表 与 总价格]
     */
    private function addProduct()
    {
        $arr            = [];
        $product        = implode(',', I('product_id'));
        $arr['product'] = M('line_additional_product')
            ->field('product_price,product_id,product_name')
            ->where(['product_id' => ['in', $product]])
            ->select();
        $arr['product_price'] = array_sum(array_map('array_shift', $arr['product']));
        return $arr;
    }

    /**
     * 交通方式座位信息
     * @param  [string] $day            时间戳
     * @param  [int]    $line_id        线路id
     * @param  [int]    $travel_days   行程天数
     * @return array
     */
    private function seatInfo($day, $line_id, $travel_days)
    {
        $back_day = date('Y-m-d', $day + ($travel_days - 1) * 86400);
        $time     = date('Y-m-d', $day);

        //线路可升级列表
        $info = M('line_upgrade_traffic as ut')
            ->field('up_traffic_id,traffic_price_id,traffic_id,now_adult_price,now_child_price,ut.seat_num,seat_name,type')
            ->join('LEFT JOIN __PUBLIC_SINGLE_TRAFFIC_PRICE__ as t on ut.traffic_price_id = t.traffic_priceId ')
            ->where(['line_id' => $line_id])
            ->select();

        $surplus_seat = [];
        $m            = M('day_traffice');
        $m_price      = M('public_single_traffic_price as t');
        $m_traffic    = M('public_single_traffic ');

        $go = $m_price
            ->field('t.traffic_priceId,seat_name,seat_num, t.traffic_id')
            ->join('__PUBLIC_SINGLE_TRAFFIC_SEAT__ as s on t.seat_id = s.seat_id and t.traffic_priceId = ' . $this->line['go_price_id'])
            ->find();
        $go['traffic_price_id'] = $go['traffic_priceId'];
        $go['type']             = 1;

        $back = $m_price
            ->field('t.traffic_priceId,seat_name,seat_num, t.traffic_id')
            ->join('__PUBLIC_SINGLE_TRAFFIC_SEAT__ as s on t.seat_id = s.seat_id and t.traffic_priceId = ' . $this->line['back_price_id'])
            ->find();
        $back['traffic_price_id'] = $back['traffic_priceId'];
        $back['type']             = 2;
        $info['go']               = $go;
        $info['back']             = $back;

        // array_unshift($info, $go, $back);
        // M()->stratTrans();
        // krsort($info,SORT_STRING);
        //查看余位
        foreach ($info as $k => $v) {
            //回的时间
            $now_day = $v['type'] == 1 ? $time : $back_day;
            $seat    = $m
                ->where(['day' => $now_day, 'traffic_priceId' => $v['traffic_price_id']])
                ->getField('surplus_seat');
            //不存在就插入数据
            if (!isset($seat)) {
                $m->add([
                    'day'             => $now_day,
                    'seat_name'       => $v['seat_name'],
                    'surplus_seat'    => $v['seat_num'],
                    'traffic_priceId' => $v['traffic_price_id'],
                ]);
            } else {
                $v['seat_num'] = $seat;
            }
            if ($k === 'go' || $k === 'back') {
                //交通工具名称
                $v['traffic_name'] = $m_traffic
                    ->where(['traffic_id' => $v['traffic_id']])
                    ->getField('traffic_name');
                $surplus_seat['standard'][$k] = $v;
                continue;
            }
            //余位为0不展示
            if ($v['seat_num']) {
                $v['type'] == 1 ? ($surplus_seat['go'][] = $v) : $surplus_seat['back'][] = $v;
            }
        }
        return $surplus_seat;
    }

    /**
     * 酒店房间信息
     * @param  [string] $day            时间戳
     * @param  [int]    $line_id        线路id
     * @param  [int]    $travel_days   行程天数
     * @return array
     */
    private function hotelInfo($day, $line_id, $travel_days)
    {

        $info = M('public_trip')
            ->field('current_day,upgrade_lodging,lodging')
            ->where(['line_id' => $line_id])
            ->select();
        $surplus = [];
        $m       = M('day_hotel');
        $m_up    = M('line_upgrade_hotel as h');
        //对每天酒店信息进行整理
        foreach ($info as $k => $v) {
            $day_up_room = $m_up
                ->field('up_hotel_id,h.room_price_id,h.user_count,now_adult_price,now_child_price,h.room_count,room_name,h.supplier_name')
                ->join('__PUBLIC_SINGLE_ROOM_PRICE__ as p on p.room_priceId = h.room_price_id  and up_hotel_id in (' . $v['upgrade_lodging'] . ')')
                ->join('LEFT JOIN __PUBLIC_SINGLE_ROOM__ as r on r.room_id = p.room_id')
                ->select();
            $now_day = date('Y-m-d', $day + 86400 * ($v['current_day'] - 1));

            $surplus[$v['current_day']]['upgrade'] = $this->roomArrange($m, $day_up_room, $now_day);
            unset($day_up_room);

            //每天的酒店
            $day_room = M('public_single_room_price as p')
                ->field('p.room_priceId,user_count,room_count,room_name,s.supplier_name')
                ->join('__PUBLIC_SINGLE_ROOM__ as r on r.room_id = p.room_id and p.room_priceId in (' . $v['lodging'] . ')')
                ->join('LEFT JOIN __PUBLIC_SINGLE_SUPPLIER__ as s on s.supplier_id = p.supplier_id')
                ->select();
            $surplus[$v['current_day']]['room'] = $this->roomArrange($m, $day_room, $now_day);
        }
        // if(session('reseller_user.reseller_id') == 7){
        //     dump($surplus);
        //     die;
        // }
        return $surplus;
    }

    /**
     * [roomArrange description]
     * @param  [class]  $m        [day_hotel表的model类]
     * @param  [array]  $day_room [每天房间信息]
     * @param  [string] $now_day  [当天日期 2017-09-09]
     * @param  [array]  $surplus  [房间信息]
     */
    private function roomArrange($m, $day_room, $now_day)
    {
        $surplus = [];
        foreach ($day_room as $kk => $vv) {
            $surplus_room = $m
                ->where(['day' => $now_day, 'room_priceId' => (isset($vv['room_price_id']) ? $vv['room_price_id'] : $vv['room_priceId'])])
                ->getField('surplus_room');
            //不存在就插入数据
            if (!isset($surplus_room)) {
                $m->add([
                    'day'          => $now_day,
                    'room_name'    => $vv['room_name'],
                    'surplus_room' => $vv['room_count'],
                    'room_priceId' => (isset($vv['room_price_id']) ? $vv['room_price_id'] : $vv['room_priceId']),
                ]);

            } else {
                $vv['room_count'] = $surplus_room;
            }

            if ($vv['room_count']) {
                $surplus[$kk] = $vv;
            }

        }
        return $surplus;
    }

}
